package com.znsd.zl.app.wechat.controller;

import com.znsd.zl.app.wechat.utils.MessageUtils;
import com.znsd.zl.app.wechat.utils.WeChatConstants;
import com.znsd.zl.app.wechat.utils.XmlUtils;
import com.znsd.zl.app.wechat.vo.req.MsgReqVO;
import com.znsd.zl.app.wechat.vo.req.SignatureReqVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * <p>
 *     微信接口交互控制器
 * </p>
 * @ClassName WeChatController
 * @Description TODO
 * @Author jaypdd
 * @Date 2020/8/23 15:42
 * @Version v1.0
 */
@RestController
@RequestMapping("/user/weChat")
@Slf4j
public class WeChatController {

	/**
	 * 微信接口请求消息验证
	 * @param reqVO     请求参数vo
	 * @return  返回随机数
	 */
	@GetMapping("/check")
	public Object checkSignature(SignatureReqVO reqVO) {
		log.info("【微信公众号】微信请求本机服务器验证成功：{}" + reqVO);
		return reqVO.getEchostr();
	}

	/**
	 * 微信公众平台消息回复
	 * @param request   请求对象
	 * @param response  响应对象
	 */
	@PostMapping(value = "/check", produces = {"application/xml;charset=utf-8"})
	public void doRequest(HttpServletRequest request, HttpServletResponse response) throws IOException {
		// 解析微信请求过来的xml文件流对象，封装到map中
		Map<String, String> map = null;
		try {
			map = XmlUtils.getMap(request.getInputStream());
		} catch (IOException e) {
			e.printStackTrace();
			log.error("【微信公众号】消息xml解析失败，失败原因：{}", map);
		}

		// 封装请求参数对象
		MsgReqVO msgReqVO = new MsgReqVO().setToUserName(map.get("ToUserName"))
				.setFromUserName(map.get("FromUserName"))
				.setCreateTime("123123")
				.setMsgType(map.get("MsgType"));

		// 判断当前请求是否为事件操作
		if ( WeChatConstants.MSG_TYPE_EVENT.toLowerCase().equals(msgReqVO.getMsgType()) ) {
			if ( WeChatConstants.SUBSCRIBE.equals(map.get(WeChatConstants.MSG_TYPE_EVENT)) ) {
				msgReqVO.setContent("欢迎您关注智联找房租房平台！");
			}
		}

		// 封装返回消息，将字符串xml标签转换成流返回给客户端
		String resultContent = "当前没有客服在线哦!";
		String result = MessageUtils.formatMsg(msgReqVO.setMsgType("text").setContent(resultContent));
		response.setCharacterEncoding("UTF-8");
		response.getWriter().write(result);
		log.info("【微信公众号】消息回复成功：{}", result);
	}



}
